// pages/derivatives/derivatives.js
const db = wx.cloud.database();
Page({
    data: {
        // 接收的参数
        derivativeId: null,
        // 分类数据
        categories: [],
        // 当前选中的分类ID
        currentCategory: "",
        // 商品数据
        products: [],
        // 分页参数
        page: 1,
        pageSize: 10,
        hasMore: true,
        isLoading: false,
        // 加载状态
        isDataLoaded: false
    },

    onLoad(options) {
        console.log(options);
        // 接收从首页传递的参数
        if (options.derivativeId) {
            this.setData({
                derivativeId: options.derivativeId
            });
        }
        console.log(this.data.derivativeId);

        this.loadCategories();
    },

    // 获取分类数据
    loadCategories() {
        wx.showLoading({
            title: '加载中...'
        });
        db.collection('derivative_type').get()
            .then(res => {
                wx.hideLoading();
                console.log(res);
                this.setData({
                    categories: res.data,
                    currentCategory: this.data.derivativeId || res.data[0]?.derivativeId || ""
                });
                this.loadProducts()
            })
            .catch(err => {
                wx.hideLoading();
                console.error('加载盲盒衍生品失败', err);
                wx.showToast({
                    title: '盲盒衍生品加载失败',
                    icon: 'none'
                });
            });
    },

    // 获取商品数据
    loadProducts() {
        this.setData({
            isLoading: true,
            page: 1,
            hasMore: true
        });
        console.log(this.data.currentCategory);
        wx.cloud.callFunction({
            name: 'getDerivativeGoods',
            data: {
                derivativeId: this.data.currentCategory,
                page: this.data.page,
                pageSize: this.data.pageSize
            },
            success: (res) => {
                console.log(res);
                if (res.result.success) {
                    res.result.data.forEach(item=>{
                        let arr = item.goodsImage.split(',')
                        if (arr.length) {
                            item.images = arr
                        }
                    })
                    const newGoodsList = this.data.page === 1 
                      ? res.result.data 
                      : [...this.data.products, ...res.result.data];
                    
                    const hasMore = newGoodsList.length < res.result.total;
                    this.setData({
                        products: newGoodsList,
                        hasMore: hasMore,
                        isDataLoaded: true
                    });
                }
            },
            fail: (err) => {
                console.error('获取商品失败:', err);
                wx.showToast({
                    title: '获取商品失败',
                    icon: 'none'
                });
            },
            complete: () => {
                this.setData({
                    isLoading: false
                });
            }
        });
    },

    // 点击分类
    onCategoryTap(e) {
        console.log(e);
        const categoryId = e.currentTarget.dataset.id;
        this.setData({
            currentCategory: categoryId,
            page: 1,
            hasMore: true
        });
        this.loadProducts();
    },

    // 点击商品进入详情页
    onProductTap(e) {
        console.log(e);
        const productId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/goods/index?goodsId=${productId}`
        });
    },

    // 下拉刷新
    onPullDownRefresh() {
        this.setData({
            page: 1,
            hasMore: true
        });
        this.loadProducts();
        wx.stopPullDownRefresh();
    },

    // 上拉加载更多
    onReachBottom() {
        if (this.data.hasMore && !this.data.isLoading) {
            this.setData({
                page: this.data.page + 1,
                isLoading: true
            });
            this.loadProducts();
        }
    }
});